package com.lee.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.lee.annotation.NotNull;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Parameter;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class ParamValidatorInterceptor implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;

        Parameter[] parameters = handlerMethod.getMethod().getParameters();

        List<String> validatorParams = Arrays.stream(parameters)
                .filter(parameter -> parameter.isAnnotationPresent(NotNull.class))
                .map(Parameter::getName)
                .collect(Collectors.toList());


        List<String> nullParams = validatorParams.stream()
                .filter(paramName -> requestParamIsNull(request, paramName))
                .collect(Collectors.toList());

        if (!nullParams.isEmpty()) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("msg", "必传参数错误");
            response.setHeader("Content-type", "application/json;charset=UTF-8");
            response.getWriter().write(jsonObject.toJSONString());
            return false;
        }

        return true;
    }

    private boolean requestParamIsNull(HttpServletRequest request, String paramName) {
        String paramValue = request.getParameter(paramName);
        if (StringUtils.isBlank(paramValue)) {
            return true;
        }
        return false;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        
    }
}
